package com.web.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.web.dao.domain.Role;

/**
 * 
 * @author NhuKhang
 *
 */

public class RoleHibernateDAO extends HibernateDaoSupport implements RoleDAO {

/* 	
	1. if do not extends HibernateDaoSupport
  
 	private HibernateTemplate hibernateTemplate;

	// if not user bean hibernateTemplate, use only SesssionFactory
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}
	//other case
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public List<Role> findAll() {
		return (List<Role>)hibernateTemplate.find("from Role");
	}
	
	2. if use HibernateDaoSupport, this class auto generator HibernateTemplate from SessionFactory or direct from HibernateTemplate
	so only support SessionFactory or HibernateTemplate
*/

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<Role> findAll() throws DataAccessException{
		//return (List<Role>)this.getHibernateTemplate().find("from Role");
		return this.getHibernateTemplate().execute(new HibernateCallback() {
			public List<Role> doInHibernate(Session session) {
				Criteria criteria = session.createCriteria(Role.class);
				return (List<Role>)criteria.list();
			}
		});
	}

	public Role save(Role role) {
		this.getHibernateTemplate().save(role);
		return role;
	}
}
